﻿using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace ClientConsole {
    public class Program {
        public static void Main(string[] args) {
            Task.Run(async () => {
                // discover endpoints from metadata
                var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
                //var disco = await DiscoveryClient.GetAsync("https://localhost:44347");

                //var tokenResponse = await GetTokenResponse(disco);
                var tokenResponse = await GetPwdTokenResponse(disco);

                // call api
                var client = new HttpClient();
                client.SetBearerToken(tokenResponse.AccessToken);

                var response = await client.GetAsync("http://localhost:5001/identity");
                if (!response.IsSuccessStatusCode) {
                    Console.WriteLine(response.StatusCode);
                    Console.ReadLine();
                }

                var content = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(JArray.Parse(content));
            }).Wait();
        }

        static async Task<TokenResponse> GetTokenResponse(DiscoveryResponse disco) {
            // request token
            var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

            if (tokenResponse.IsError) {
                Console.WriteLine("error: " + tokenResponse.Error);
                Console.ReadLine();
            }

            Console.WriteLine(tokenResponse.Json);
            return tokenResponse;
        }

        static async Task<TokenResponse> GetPwdTokenResponse(DiscoveryResponse disco) {

            // request token
            var tokenClient = new TokenClient(disco.TokenEndpoint, "ro.client", "secret");
            var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync("zicjin", "z5656z", "api1");

            if (tokenResponse.IsError) {
                Console.WriteLine("error: " + tokenResponse.Error);
                Console.ReadLine();
            }

            Console.WriteLine(tokenResponse.Json);
            return tokenResponse;
        }
    }
}
